# Importing Data
AUSTRALIA <- read_excel("C:/Users/Biniam/Desktop/Documents/Academic/Thesis/Analysis Folder/Excel Files/Oman/Australia.xlsx")

# Checking the Imported Data
View(AUSTRALIA)

# Creating Time Series Data
AUSTRALIA_ts <- ts(AUSTRALIA, start=c(2004,1), end=c(2017,07), frequency=12)

# Viewing and Checking the Created Time Series Data
AUSTRALIA_ts
sum(is.na(AUSTRALIA_ts))
library(forecast)
AUSTRALIA_ts <- tsclean(AUSTRALIA_ts)

# Step – 1 of the Box-Jenkins Methodology (Identification: Plotting the Time Series Data)
plot(AUSTRALIA_ts)
plot(aggregate(AUSTRALIA_ts,FUN=mean))

# Decomposing
AUSTRALIA_ts_decomp <- decompose(AUSTRALIA_ts)
plot(AUSTRALIA_ts_decomp)

# Testing for Stationarity
acf(AUSTRALIA_ts, lag.max=20)
pacf(AUSTRALIA_ts, lag.max=20)

# To see any seasonal effect
boxplot(AUSTRALIA_ts~cycle(AUSTRALIA_ts))

# To remove trend effect
AUSTRALIA_ts_diff <- diff(AUSTRALIA_ts)
plot(AUSTRALIA_ts_diff)

# To remove variance effect
AUSTRALIA_ts_log <- log(AUSTRALIA_ts)
plot(AUSTRALIA_ts_log)

# To remove both (Trend and Variance) effects
AUSTRALIA_ts_both <- diff(log(AUSTRALIA_ts))
plot(AUSTRALIA_ts_both)


# Dealing with ACF and PACF
install.packages("tseries")
library(tseries)
acf(AUSTRALIA_ts, lag.max=20)
acf(log(AUSTRALIA_ts), lag.max=20)
acf(diff(AUSTRALIA_ts), lag.max=20)
acf(diff(log(AUSTRALIA_ts)), lag.max=20)
pacf(AUSTRALIA_ts, lag.max=20)
pacf(log(AUSTRALIA_ts), lag.max=20)
pacf(diff(AUSTRALIA_ts), lag.max=20)
pacf(diff(log(AUSTRALIA_ts)), lag.max=20)

# Step-2 of the Box-Jenkins Methodology (Estimating the appropriate model)
AUSTRALIA_ts_model <- auto.arima(AUSTRALIA_ts)
AUSTRALIA_ts_model
AUSTRALIA_ts_model <- auto.arima(AUSTRALIA_ts, ic="aic", trace = TRUE)
AUSTRALIA_ts_model

# Step-3 of the Box-Jenkins Methodology (Diagnosis Checking)
library(tseries)
plot.ts(AUSTRALIA_ts_model$resid)
acf(AUSTRALIA_ts_model$residuals, main='ACF Residual')
pacf(AUSTRALIA_ts_model$residuals, main='ACF Residual')
Box.test(AUSTRALIA_ts_model$resid, lag=20, type="Ljung-Box")

# Forecasting
options(max.print=1000000)
library(forecast)
AUSTRALIA_ts_forecast <- forecast (AUSTRALIA_ts_model, level=c(95), h=281)
plot(AUSTRALIA_ts_forecast)
AUSTRALIA_ts_forecast             


write.table(AUSTRALIA_ts_forecast, file="Australia_TSA.csv", sep=",")
